// pages/addressAdd/addressAdd.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address:'' //省市区
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const formWeb = options.formWeb;
    if (formWeb == 'order') {
      this.setData({
        formWeb: 'order'
      });
    }
  },

  //选择省市区
  regionChange(e){
    this.setData({
      address: e.detail.value
    })
  },

  //提交数据
  formSubmit: function (e) {
    const userId = app.globalData.userId;
    const shperson = e.detail.value.username, //收货人姓名
      mobile = e.detail.value.mobile, //收货人手机号
      region = e.detail.value.region.join('') || this.data.address, //收货地址
      detail_info = e.detail.value.detail, //详细地址
      status = e.detail.value.default - 0; //是否默认，布尔值转换成数字
    const reg = /^1[23456789]\d{9}$/;
    console.log(status)
    //进行验证判断
    if (!shperson) { this.toast('请输入收货人'); return; }
    if (!mobile) { this.toast('请输入联系电话'); return;}
    if (!reg.test(mobile)) { this.toast('手机号格式不正确'); return;}
    if (!region) { this.toast('请选择省市区'); return; }
    if (!detail_info) { this.toast('请输入详细地址'); return; }
    
    //发送网络请求
    wx.request({
      url: app.baseURL +'Mine&a=add_address',
      data: {
        user_id: userId,
        shperson: shperson,
        mobile: mobile,
        region: region,
        detail_info: detail_info,
        status: status 
      },
      success: (res) => {
        console.log(res)
        if (res.data.status == 5) {
          let addressInfo = res.data.address_info;
          //如果从下单详情页面进入的本页面
          if (this.data.formWeb) this.formOrder(addressInfo);
          //返回上一页
          wx.navigateBack();
        } else if (res.data.status == 6) this.toast('添加失败，请重试'); 
      },
      fail: (res) => { this.toast('网络错误！'); }
    })
  },

  //如果是从下单详情页面进来
  //添加地址完成后要返回下单详情页面,并且更新地址信息
  formOrder(add_res) {
    //获取页面栈
    let pages = getCurrentPages();
    //获取上一个页面
    let prev = pages[pages.length - 2];
    //调用上一个页面的setData方法，从而达到naviagtreBack返回传参的效果
    //简单粗暴
    prev.setData({
      add_res: add_res //添加的地址数据
    });
  },

  //简化提示函数
  toast(msg) {
    wx.showToast({
      title: msg,
      icon: 'none'
    })
  },

  // 同步微信地址
  getCity() {
    let that = this;
    wx.chooseAddress({
      success (res) {
        console.log(res);
        that.setData({
          shperson: res.userName, 
          mobile: res.telNumber,
          address: res.provinceName + "," + res.cityName + "," + res.countyName,
          detail_info: res.detailInfo
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  }
})